<?php

namespace App\Admin\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Agent;
use App\Withdraw;
use App\RebateLog;

class WithdrawController extends Controller
{
	/*游戏对应商户*/
	protected $config = [
    	'app_id' => 'wxb19dc538de82d329',
	    'secret' => 'a14a0d4744840960f16866056f7da387',
	    // payment
	    'payment' => [
	        'merchant_id' => '1502450861',
	        'key' => 'leyouleyouleyouleyouleyouleyou18',
	    	'cert_path' => '/home/app_cert/apiclient_cert.pem',
	    	'key_path' => '/home/app_cert/apiclient_key.pem',
	    ],
	    'log' => [
	    ],
	];

	/**
	 * [index description]
	 * @return [type] [description]
	 */
	public function index(Request $request)
	{
		$datas = Withdraw::where(['status' => 0])->paginate(15);

		return view('admin.withdraw.index', compact('datas'));
	}

	/**
	 * [audit description]
	 * @return [type] [description]
	 */
	public function audit(Withdraw $withdraw)
	{
		return view('admin.withdraw.audit', compact('withdraw'));
	}

	/**
	 * [docash description]
	 * @return [type] [description]
	 */
	public function docash(Withdraw $withdraw, Request $request)
	{
		if ($request->input('status') == 1) {//同意提现
			if ($withdraw->is_super == 1) {
				$result = $this->superWithdraw($withdraw);
			} else {
				$result = $this->withdraw($withdraw);
			}
			if ($result) {
				$withdraw->status = $request->input('status');
			}
		} else {//驳回
			$withdraw->status = $request->input('status');
			$withdraw->reason = $request->input('reason');
			if ($withdraw->is_super == 1) {
				$agent = $withdraw->superagent;
			} else {
				$agent = $withdraw->agent;
			}
			$agent = $withdraw->agent;
			$agent->money += $withdraw->money;
			$agent->save();
		}
		$withdraw->save();

		return redirect('/admin/withdraw/list');
	}

	/**
	 * [withdraw description]
	 * @return [type] [description]
	 */
	public function withdraw($withdraw)
	{
    	$app = new Application($this->config);
		$merchantPay = $app->merchant_pay;
        $merchantPayData = [
            'partner_trade_no' => str_random(16), //随机字符串作为订单号，跟红包和支付一个概念。
            'openid' => $withdraw->agent->user()->open_id, //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'张三',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => $withdraw->money * 100,  //单位为分
            'desc' => '企业付款',
            'spbill_create_ip' => '47.95.202.91',  //发起交易的IP地址
        ];
        $result = $merchantPay->send($merchantPayData);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
        	$withdraw->status = 1;
        	$withdraw->save();
        	return true;
        } 
        return false;
	}

	public function superWithdraw($withdraw)
	{
    	$app = new Application($this->config);
		$merchantPay = $app->merchant_pay;
        $merchantPayData = [
            'partner_trade_no' => str_random(16), //随机字符串作为订单号，跟红包和支付一个概念。
            'openid' => $withdraw->superagent->user()->open_id, //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'张三',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => $withdraw->money * 100,  //单位为分
            'desc' => '企业付款',
            'spbill_create_ip' => '47.95.202.91',  //发起交易的IP地址
        ];
        $result = $merchantPay->send($merchantPayData);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
        	$withdraw->status = 1;
        	$withdraw->save();
        	return true;
        } 
        return false;
	}

	/**
	 * [remove 删除提现记录]
	 * @return [type] [description]
	 */
	public function remove(Withdraw $withdraw)
	{
		$withdraw->delete();
		return back();
	}

	/**
	 * [source 收入来源]
	 * @return [type] [description]
	 */
	public function source(Withdraw $withdraw)
	{
		$logs = RebateLog::where(['daili_id' => $withdraw->agent_id])->orderBy('created_at', 'DESC')->limit(3)->get();
		$total = RebateLog::select(DB::raw('SUM(fee)'))->where(['daili_id' => $withdraw->agent_id])->value('SUM(fee)');
		$number = RebateLog::where(['daili_id' => $withdraw->agent_id])->count();
		return view('admin.withdraw.source', compact('logs', 'total', 'withdraw', 'number'));
	}

	/**
	 * [loadSource 加载来源]
	 * @return [type] [description]
	 */
	public function loadSource(Request $request, Withdraw $withdraw)
	{
		if (!$request->input('page')) {
			return ['flag' => false, 'msg' => 'page不能为空'];
		}
		if (!$request->input('pagesize')) {
			return ['flag' => false, 'msg' => 'pagesize不能为空'];
		}
		$limit = ($request->input('page') - 1) * $request->input('pagesize');
		$data = RebateLog::where(['daili_id' => $withdraw->agent_id])->orderBy('created_at', 'DESC')->offset($limit)->limit($request->input('pagesize'))->get();
		if ($data) {
			return ['flag' => true, 'data' => $data];
		} else {
			return ['flag' => false, 'msg' => '暂无更多'];
		}
	}

	/**
	 * [check 金额检查]
	 * @return [type] [description]
	 */
	public function check(Withdraw $withdraw)
	{
		$total_fee = Withdraw::select(DB::raw('SUM(money)'))->where(['agent_id' => $withdraw->agent_id, 'status' => 1])->value('SUM(money)');//提现成功总额度
		$total_rebate = RebateLog::select(DB::raw('SUM(fee)'))->where(['daili_id' => $withdraw->agent_id])->value('SUM(fee)');//返利总收益
		$agent = Agent::where(['id' => $withdraw->agent_id])->first();
		$result = (($agent->money + $total_fee + $withdraw->money) <= $total_rebate) ? true: false;
		$re_arr = [
			'current_money' => $agent->money,
			'total_withdraw' => $total_fee,
			'total_rebate' => $total_rebate,
			'current_withdraw' => $withdraw->money,
			'result' => $result
		];

		return view('admin.withdraw.check', compact('re_arr'));
	}

	/**
	 * [log 提现记录]
	 * @return [type] [description]
	 */
	public function log(Request $request)
	{
		$keywords = $request->input('keywords');
		$time = $request->input('time');
		$datas = Withdraw::select(DB::raw('withdraw.agent_id, withdraw.money, withdraw.status, withdraw.reason, withdraw.created_at, withdraw.updated_at, m_dailis.realname, m_dailis.nickname,(SELECT SUM(money) FROM withdraw WHERE withdraw.status = 1) AS amount'))->join('m_dailis', function($join){
			$join->on('withdraw.agent_id', '=', 'm_dailis.id');
		})->whereIn('withdraw.status', [1, 2])->orderBy('withdraw.created_at', 'DESC');
		if ($time) {
			$time_arr = explode('~', $time);
			$begin = $time_arr[0];
			$end = $time_arr[1];
			$datas = $datas->where(function($query) use ($begin, $end) {
				$query->whereBetween('withdraw.created_at', [$begin, $end])->orWhere(function($ruery) use ($begin, $end){
					$ruery->whereBetween('withdraw.updated_at', [$begin, $end]);
				});
			});
		}
		if ($keywords) {
			$datas = $datas->where('m_dailis.realname', 'like', '%'.$keywords.'%')->orWhere(function($query) use ($keywords){
				$query->where('nickname', 'like', '%'.$keywords.'%');
			});
		}
		$datas = $datas->paginate(15);
		$datas->appends([
				'keywords' => $keywords,
				'time' => $time
			]);
		
		return view('admin.withdraw.log', compact('datas', 'keywords', 'time'));
	}


}	